const { Controller } = require('egg');

class LoginJwtController extends Controller {
    async login() {
        const { userName, password } = this.ctx.request.body
        if (userName === 'ethink' && password === '123456') {
            // 生成token
            let token = this.app.jwt.sign({userName, password}, this.app.config.jwt.secret)
            console.log(token);
            this.ctx.body = {
                code: 20000, 
                message: "登录成功",
                token
            }
        } else {
            this.ctx.body = {code: 40000, message: "用户名或密码错误"}
        }
    }

    // 需要token才能获取数据
    async getMessage() {
        let token = this.ctx.request.header.token
        // token校验
        try {
            // token解析后的数据
            const result = this.app.jwt.verify(token, this.app.config.jwt.secret)
            this.ctx.body = {code: 20000, data: result}
        } catch (e) {
            this.ctx.body = {code: 40000, message: "token未通过校验"}
        }
    }

    // 中间件校验token,不用在这里校验
    async getMessage1() {
        this.ctx.body = {code: 20000, data: "hello world"}
    }
}

module.exports = LoginJwtController;